/**

 @Name：layuiAdmin 用户登入和注册等


 @License: LPPL

 */

layui.define('form', function (exports) {
    var $ = layui.$
        , layer = layui.layer
        , laytpl = layui.laytpl
        , setter = layui.setter
        , table = layui.table
        , admin = layui.admin
        , form = layui.form;

    var $body = $('body');

    //自定义验证
    form.verify({
        nickname: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                return '用户名不能有特殊字符';
            }
            if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                return '用户名首尾不能出现下划线\'_\'';
            }
            if (/^\d+\d+\d$/.test(value)) {
                return '用户名不能全为数字';
            }
        }

        //我们既支持上述函数式的方式，也支持下述数组的形式
        //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
        , pass: [
            /^[\S]{6,12}$/
            , '密码必须6到12位，且不能出现空格'
        ]
    });

    //更换图形验证码
    $body.on('click', '#LAY-user-get-vercode', function () {
        var othis = $(this);
        if (this.src.indexOf("?") !== -1) {
            this.src = this.src.substr(0, this.src.lastIndexOf("?")) + '?t=' + new Date().getTime()
        } else {
            this.src = this.src + '?t=' + new Date().getTime()
        }
    });

    //用户管理
    table.render({
        elem: '#LAY-user-manage'
        , url: 'user'
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'id', width: 100, title: 'ID', sort: true}
            , {field: 'username', title: '用户名', minWidth: 100}
            , {field: 'avatar', title: '头像', width: 100, templet: '#imgTpl'}
            , {field: 'mobile', title: '手机'}
            , {field: 'email', title: '邮箱'}
            , {field: 'sex', width: 80, title: '性别'}
            , {field: 'ip', title: 'IP'}
            , {field: 'create_time', title: '加入时间', sort: true}
            , {title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#LAY-user-user-bar'}
        ]]
        , page: true
        , limit: 10
        , height: 'full-320'
        , text: '对不起，加载出现异常！'
    });

    form.render(null, 'layadmin-userfront-formlist');

    //监听搜索
    form.on('submit(LAY-user-front-search)', function (data) {
        var field = data.field;

        //执行重载
        table.reload('LAY-user-manage', {
            where: field
        });
    });

    //事件
    var active = {
        batchdel: function () {
            var checkStatus = table.checkStatus('LAY-user-manage')
                , checkData = checkStatus.data; //得到选中的数据

            if (checkData.length === 0) {
                return layer.msg('请选择数据');
            }

            layer.prompt({
                formType: 1
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                layer.close(index);

                layer.confirm('确定删除吗？', function (index) {
                    admin.req({
                        url: 'user'
                        , data: {ids: checkData.map(x => {return x.id})}
                        , type: "DELETE"
                        , done: function (res) {
                            if (res.code === 0) {
                                layer.msg(res.message, {icon: 6});
                                table.reload('LAY-user-manage');
                                layer.close(index);
                            } else {
                                layer.msg(res.message, {icon: 5});
                            }
                        }
                    });
                });
            });
        }
        , add: function () {
            layer.open({
                type: 2
                , title: '添加用户'
                , content: 'user/create'
                , area: ['500px', '480px']
                , btn: ['确定', '取消']
                , yes: function (index, layero) {
                    var iframeWindow = window['layui-layer-iframe' + index]
                        ,submitID = 'LAY-user-user-submit'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);

                    //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(data){
                        $.ajax({
                            url: 'user',
                            data: data.field,
                            type: "post",
                            dataType: "json",
                            success: function (res) {
                                if (!res.code) {
                                    layer.msg(res.message, {icon: 6});
                                    table.reload('LAY-user-manage');
                                    layer.close(index); //关闭弹层
                                } else {
                                    layer.msg(res.message, {icon: 5});
                                }
                            },
                            error: function (res) {
                                layer.msg(res.responseJSON.message, {icon: 5});
                            }
                        });

                    });

                    submit.trigger('click');
                }
            });
        }
    };

    $('.layui-btn.layuiadmin-btn-useradmin').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    //监听工具条
    table.on('tool(LAY-user-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.prompt({
                formType: 1
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                layer.close(index);

                layer.confirm('真的删除行么', function (index) {
                    admin.req({
                        url: 'user/' + data.id
                        , type: "delete"
                        , done: function (res) {
                            obj.del();
                            layer.close(index);
                        }
                    });
                });
            });
        } else if (obj.event === 'edit') {
            layer.open({
                type: 2
                ,title: '编辑用户'
                ,content: 'user/' + data.id + '/edit'
                ,area: ['500px', '450px']
                ,btn: ['确定', '取消']
                ,resize: false
                ,yes: function(index, layero){
                    var iframeWindow = window['layui-layer-iframe'+ index]
                        ,submitID = 'LAY-user-user-submit'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);

                    //监听提交
                    iframeWindow.layui.form.on('submit('+ submitID +')', function(formData){
                        admin.req({
                            url: 'user/' + data.id
                            , data: formData.field
                            , type: "PUT"
                            , done: function (res) {
                                if (!res.code) {
                                    layer.msg(res.message, {icon: 6});
                                    obj.update(formData.field);
                                } else {
                                    layer.msg(res.message, {icon: 5});
                                }
                                layer.close(index);
                            }
                        });
                    });

                    submit.trigger('click');
                }
            });
        }
    });

    //对外暴露的接口
    exports('user', {});
});